// #ifdef APP-PLUS
const RecNP = uni.requireNativePlugin('Recorder-NativePlugin-Android');
// #endif

const listenersMap = {
    onRecord: new Set(),
    onRecError: new Set(),
    onPcmPlayerEvent: new Set(),
    onLog: new Set(),
    onInterruptionBegin: new Set(),
    onInterruptionEnd: new Set(),
};

let boundJsCall = false;

function dispatch(eventName, data) {
    const set = listenersMap[eventName];
    if (!set || set.size === 0) return;
    set.forEach(fn => {
        try {
            fn(data);
        } catch (e) {
            console.error('[RecNPManager] listener error', e);
        }
    });
}

function bindJsCallOnce() {
    // #ifdef APP-PLUS
    if (boundJsCall) return;
    boundJsCall = true;
    RecNP.request({ action: 'jsCall', args: {} }, data => {
        if (!data || !data.action) return;
        // 统一分发：data.action 如 onRecord/onRecError/onPcmPlayerEvent/onLog 等
        dispatch(data.action, data);
    });
    // #endif
}

function call(action, args = {}) {
    // #ifdef APP-PLUS
    bindJsCallOnce();
    return new Promise((resolve, reject) => {
        RecNP.request({ action, args }, res => {
            if (!res || res.status !== 'success') {
                reject(new Error((res && res.message) || 'native call failed'));
                return;
            }
            resolve(res.value);
        });
    });
    // #endif
}

function on(eventName, handler) {
    // #ifdef APP-PLUS
    const set = listenersMap[eventName];
    if (!set) return;
    set.add(handler);
    bindJsCallOnce();
    // #endif
}

function off(eventName, handler) {
    // #ifdef APP-PLUS
    const set = listenersMap[eventName];
    if (!set) return;
    set.delete(handler);
    // #endif
}

export default {
    call,
    on,
    off,
    bindJsCallOnce,
};
